<template>
  <el-dialog
    :title="mode === 'edit' ? '修改备件' : '新增备件'"
    v-model="visibleInner"
    width="90%"
    append-to-body
    @open="onOpen"
    @close="onClose"
    class="fix-footer-dialog"
    :style="{ '--dlg-h': dialogHeight }"
  >
    <!-- 主信息 -->
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="160px"
      class="top-form"
    >
      <!-- 备件信息模块 -->
      <div class="form-module">
        <h3>备件信息</h3>
        <el-row :gutter="12">
          <el-col :span="6">
            <el-form-item label="备件编码" prop="code">
              <el-input
                v-model="form.code"
                :disabled="mode === 'edit' && lockCodeOnEdit"
                placeholder="唯一，必填，大写字母"
                maxlength="64"
                @input="onCodeInput"
                inputmode="latin"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备件名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入备件名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备件类型" prop="isSpecial">
              <el-select v-model="form.isSpecial" style="width: 100%">
                <el-option
                  v-for="t in typeOptionsInner"
                  :key="t.value"
                  :label="t.label"
                  :value="t.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="采购周期(天)" prop="orderDate">
              <el-input-number
                v-model="form.orderDate"
                :min="0"
                :precision="0"
                :step="1"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 基本信息模块 -->
      <div class="form-module">
        <h3>基本信息</h3>
        <el-row :gutter="12">
          <el-col :span="6">
            <el-form-item label="规格" prop="specification">
              <el-input v-model="form.specification" placeholder="请输入规格" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="型号" prop="model">
              <el-input v-model="form.model" placeholder="请输入型号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="材质" prop="material">
              <el-input v-model="form.material" placeholder="请输入材质" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="form.brand" placeholder="请输入品牌" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="厂商" prop="manufacturer">
              <el-input v-model="form.manufacturer" placeholder="请输入厂商" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 库存信息模块 -->
      <div class="form-module">
        <h3>库存信息</h3>
        <el-row :gutter="12">
          <el-col :span="6">
            <el-form-item label="最低库存" prop="minStock">
              <el-input-number
                v-model="form.minStock"
                :min="0"
                :precision="0"
                :step="1"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="最高库存" prop="maxStock">
              <el-input-number
                v-model="form.maxStock"
                :min="0"
                :precision="0"
                :step="1"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="总库存" prop="stockTotal">
              <el-input-number
                v-model="form.stockTotal"
                :min="0"
                :precision="0"
                :step="1"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="当前库存" prop="stockAvailable">
              <el-input-number
                v-model="form.stockAvailable"
                :min="0"
                :precision="0"
                :step="1"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 备件所属模块 -->
      <div class="form-module">
        <h3>其他信息</h3>
        <el-row :gutter="12">
          <el-col :span="6">
            <el-form-item label="备件所属" prop="spareClass">
              <el-select
                v-model="form.spareClass"
                placeholder="请选择备件所属"
                @change="handleParentTypeChange"
                clearable
              >
                <el-option label="部件" value="COMPONENT" />
                <el-option label="零件" value="PART" />
                <el-option label="子设备" value="MODULE" />
                <el-option label="母设备" value="MACHINE" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="showAdvancedFields" :span="6">
            <el-form-item label="设计温度(℃)" prop="designTemp">
              <el-input-number
                v-model="form.designTemp"
                placeholder="请输入设计温度"
                :min="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="showAdvancedFields" :span="6">
            <el-form-item label="设计压力(MPa)" prop="designPress">
              <el-input-number
                v-model="form.designPress"
                placeholder="请输入设计压力"
                :min="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="showAdvancedFields" :span="6">
            <el-form-item label="电机功率(KW)" prop="motorPower">
              <el-input-number
                v-model="form.motorPower"
                placeholder="请输入电机功率"
                :min="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="12">
          <el-col :span="24">
            <el-form-item label="备注说明" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="2"
                placeholder="请输入备注说明"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="submit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from "vue";
import { ElMessage } from "element-plus";

const props = defineProps({
  visible: { type: Boolean, default: false },
  mode: { type: String, default: "add" }, // 'add' | 'edit'
  lockCodeOnEdit: { type: Boolean, default: true },
  model: { type: Object, default: () => ({}) },
  unitOptions: {
    type: Array,
    default: () => ["个", "台", "套", "米", "公斤"].map((v) => ({ label: v, value: v })),
  },
  statusOptions: {
    type: Array,
    default: () => [
      { label: "启用", value: 0 },
      { label: "停用", value: 1 },
    ],
  },
  typeOptions: {
    type: Array,
    default: () => [
      { label: "普通", value: 0 },
      { label: "特殊备件", value: 1 },
    ],
  },
  submitting: { type: Boolean, default: false },
  dialogHeight: { type: String, default: "82vh" },
});

const emit = defineEmits(["update:visible", "submit", "open"]);

const visibleInner = computed({
  get: () => props.visible,
  set: (v) => emit("update:visible", v),
});

const unitOptionsInner = computed(() => props.unitOptions);
const statusOptionsInner = computed(() => props.statusOptions);
const typeOptionsInner = computed(() => props.typeOptions);

const formRef = ref();
const form = reactive({
  id: null,
  code: "",
  name: "",
  specification: "",
  model: "",
  material: "",
  brand: "",
  manufacturer: "",
  spareClass: "PART",
  designTemp: null,
  designPress: null,
  motorPower: null,
  minStock: 0,
  maxStock: 0,
  stockTotal: 0,
  stockAvailable: 0,
  isSpecial: 0, // Changed from isSpecial to match parent component
  status: 0,
  orderDate: 0,
  remark: "",
});

// Dynamically show advanced fields based on spareClass
const showAdvancedFields = computed(() => ["MODULE", "MACHINE"].includes(form.spareClass));

// Enhanced validation rules
const rules = reactive({
  code: [
    { required: true, message: "备件编码必填", trigger: "blur" },
    {
      pattern: /^[A-Z0-9]+$/,
      message: "备件编码只能包含大写字母和数字",
      trigger: "blur",
    },
  ],
  name: [{ required: true, message: "备件名称必填", trigger: "blur" }],
  spareClass: [{ required: true, message: "备件所属必选", trigger: "change" }],
  minStock: [
    { required: true, message: "最低库存必填", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value > form.maxStock) {
          callback(new Error("最低库存不能大于最高库存"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  maxStock: [
    { required: true, message: "最高库存必填", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value < form.minStock) {
          callback(new Error("最高库存不能小于最低库存"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  stockTotal: [
    { required: true, message: "总库存必填", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value < form.stockAvailable) {
          callback(new Error("总库存不能小于当前库存"));
        } else if (value > form.maxStock) {
          callback(new Error("总库存不能大于最高库存"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  stockAvailable: [
    { required: true, message: "当前库存必填", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value > form.stockTotal) {
          callback(new Error("当前库存不能大于总库存"));
        } else if (value < 0) {
          callback(new Error("当前库存不能为负数"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
});

// Initialize form when dialog opens or mode/model changes
watch(
  () => [props.mode, props.model],
  ([newMode, newModel]) => {
    resetForm();
    if (newMode === "edit" && newModel) {
      Object.assign(form, {
        id: newModel.id || null,
        code: newModel.code || "",
        name: newModel.name || "",
        specification: newModel.specification || "",
        model: newModel.model || "",
        material: newModel.material || "",
        brand: newModel.brand || "",
        manufacturer: newModel.manufacturer || "",
        spareClass: (newModel.spareClass == null || newModel.spareClass == 0)
  ? "PART"
  : newModel.spareClass,
        designTemp: newModel.designTemp || null,
        designPress: newModel.designPress || null,
        motorPower: newModel.motorPower || null,
        minStock: newModel.minStock || 0,
        maxStock: newModel.maxStock || 0,
        stockTotal: newModel.stockTotal || 0,
        stockAvailable: newModel.stockAvailable || 0,
        isSpecial: newModel.isSpecial || 0, // Align with parent component's field name
        status: newModel.status || 0,
        orderDate: newModel.orderDate || 0,
        remark: newModel.remark || "",
      });
    }
  },
  { immediate: true }
);

// Reset form when dialog closes or mode switches
function resetForm() {
  Object.assign(form, {
    id: null,
    code: "",
    name: "",
    specification: "",
    model: "",
    material: "",
    brand: "",
    manufacturer: "",
    spareClass: "PART",
    designTemp: null,
    designPress: null,
    motorPower: null,
    minStock: 0,
    maxStock: 0,
    stockTotal: 0,
    stockAvailable: 0,
    isSpecial: 0,
    status: 0,
    orderDate: 0,
    remark: "",
  });
  formRef.value?.resetFields();
}

// Handle spareClass change
function handleParentTypeChange(value) {
  if (!["MODULE", "MACHINE"].includes(value)) {
    form.designTemp = null;
    form.designPress = null;
    form.motorPower = null;
  }
}

// Handle code input (force uppercase)
function onCodeInput(value) {
  form.code = value.toUpperCase();
}

// Submit form
function submit() {
  formRef.value.validate((valid) => {
    if (valid) {
      const payload = { ...form };
      emit("submit", payload);
    } else {
      ElMessage.error("请检查表单输入");
    }
  });
}

// Close dialog
function close() {
  visibleInner.value = false;
}

// Handle dialog open
function onOpen() {
  emit("open");
}

// Handle dialog close
function onClose() {
  resetForm();
}

defineExpose({ open: () => (visibleInner.value = true), close });
</script>

<style scoped>
.form-module {
  margin-bottom: 24px;
}

.form-module h3 {
  margin: 10px 0;
  font-size: 18px;
  font-weight: 600;
  color: #409eff;
}

.top-form :deep(.el-form-item) {
  margin-bottom: 16px !important;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.el-dialog__body {
  padding: 20px 30px;
}
</style>